package com.mg.admin.controller.admin;


import com.mg.admin.bean.admin.ResourceVO;
import com.mg.admin.bean.admin.Result;
import com.mg.admin.bean.admin.UserVO;
import com.mg.admin.constants.Constants;
import com.mg.admin.constants.ResultEnum;
import com.mg.admin.controller.BaseController;
import com.mg.admin.service.admin.ResourceService;
import com.mg.admin.service.admin.UserService;
import com.xiaoleilu.hutool.crypto.SecureUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;


@Controller
@RequestMapping("/admin/")
public class IndexController extends BaseController {


    @Autowired
    private ResourceService resourceService;

    @Autowired
    private UserService userService;

    @RequestMapping(value="login",method = RequestMethod.GET)
    public void login(){
    }


    @ResponseBody
    @RequestMapping(value="login",method = RequestMethod.POST)
    public Result<String> loginSubmit(UserVO userVO){
        Subject subject = SecurityUtils.getSubject();
        userVO.setPassword(SecureUtil.md5(userVO.getPassword()));
        UsernamePasswordToken token = new UsernamePasswordToken(userVO.getUsername(), userVO.getPassword());
        try {
            subject.login(token);
        }catch (UnknownAccountException e) {
            return new Result<>(ResultEnum.USERNAME_PASSWORD_ERROR);
        } catch (IncorrectCredentialsException e) {
            return new Result<>(ResultEnum.USERNAME_PASSWORD_ERROR);
        }catch (LockedAccountException e){
            return new Result<>(ResultEnum.USER_HAS_LOCKER);
        }catch (AuthenticationException e) {
            return new Result<>(ResultEnum.OTHER_ERROR);
        }
        userVO.setLastLoginTime(new Date());
        userVO.setLoginIp(subject.getSession().getHost());
        userService.updateByUserName(userVO);

        return new Result<>("/admin/index");
    }


    @RequestMapping(value = "index",method = RequestMethod.GET)
    public String index(ModelMap modelMap){
        UserVO userVO = currentUser();
        String resourceId = userVO.getResourceIds();
        List<ResourceVO> result = resourceService.findById(resourceId);
        modelMap.put("list",result);
        modelMap.put("bean",userVO);
        return "admin/index";
    }


    @RequestMapping(value = "logout",method = RequestMethod.GET)
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        session.removeAttribute(Constants.SESSION_KEY);
        return "admin/login";
    }








}